
<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-form ref="queryForm" :model="queryParams" :inline="true">
          <el-form-item label="题目" prop="content">
            <el-input
              v-model="queryParams.content"
              placeholder="请输入"
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="科目" prop="subject">
            <el-select v-model="queryParams.subject" filterable placeholder="请选择科目">
              <el-option
                v-for="(item, index) in subjectList"
                :key="index"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="题目类型" prop="subject_type">
            <el-select v-model="queryParams.subject_type" placeholder="请选择类型" size="small">
              <el-option
                v-for="(item,index) in topicType"
                :key="index"
                :label="item"
                :value="index"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb10" style="float:right">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
        </el-row>

        <el-table
          v-loading="loading"
          :data="dataList"
          border
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChang"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            type="index"
            header-align="center"
            width="50"
            label="序号"
            fixed="left"
            align="center"
          />
          <el-table-column header-align="center" prop="subject_type" label="题型">
            <template slot-scope="scope">
              <span>{{ topicType[scope.row.subject_type] }}</span>
            </template>
          </el-table-column>
          <el-table-column header-align="center" prop="subject" label="科目" />
          <el-table-column
            header-align="center"
            prop="content"
            :show-overflow-tooltip="true"
            label="题目"
          >
            <template slot-scope="scope">
              <el-image v-if="urlTest.test(scope.row.content)" :src="scope.row.content" />
              <span v-else v-html="scope.row.content" />
            </template>
          </el-table-column>
          <el-table-column header-align="center" prop="creator" label="创建者" />
          <el-table-column label="创建时间" align="center" prop="createdAt" width="200">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="120"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                :disabled="!multiple && single"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                :disabled="!multiple && single"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
              <!-- <el-button size="mini" type="text" icon="el-icon-view">
                <router-link
                  :to="{
                    name: 'view',
                    params: {id: scope.row.finance_txmx_id },
                  }"
                >查看</router-link>
              </el-button>-->
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-card>

      <el-drawer
        ref="drawer"
        :title="title + '习题'"
        :visible.sync="visible"
        direction="rtl"
        custom-class="demo-drawers"
        size="40%"
        @closed="reset"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="科目" prop="subject">
            <el-select v-model="form.subject" filterable placeholder="请选择科目" style="width: 100%">
              <el-option
                v-for="(item, index) in subjectList"
                :key="index"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="题目类型" prop="subject_type">
            <el-select
              v-model="form.subject_type"
              filterable
              placeholder="请选择类型"
              style="width: 100%"
              @change="changeType"
            >
              <el-option
                v-for="(item,index) in topicType"
                :key="index"
                :label="item"
                :value="index"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="题目内容" prop="content">
             <Ckeditor v-model="form.content" :content="form.content" />
<!--            <el-row>-->
<!--              <el-col :span="20">-->
<!--                <div v-if="topicContent" style="display: flex">-->
<!--                  <img :src="topicContent" class="avatar">-->
<!--                  <i-->
<!--                    class="el-icon-delete"-->
<!--                    style="margin: auto auto auto 10px;cursor: pointer"-->
<!--                    @click="(event)=>beforeRemove(topicContent)"-->
<!--                  />-->
<!--                </div>-->

<!--                <el-input-->
<!--                  v-else-->
<!--                  v-model="form.content"-->
<!--                  type="textarea"-->
<!--                  :rows="3"-->
<!--                  placeholder="请输入内容"-->
<!--                />-->
<!--              </el-col>-->
<!--              <el-col :span="4">-->
<!--                <el-upload-->
<!--                  :headers="headers"-->
<!--                  class="upload-demo"-->
<!--                  style="width: 40%"-->
<!--                  :action="$uploadUrl"-->
<!--                  :on-success="handleSuccess"-->
<!--                  :show-file-list="false"-->
<!--                >-->
<!--                  <div>-->
<!--                    <el-button-->
<!--                      type="text"-->
<!--                      icon="el-icon-picture-outline"-->
<!--                      style="margin-left: 20px;font-size: 20px"-->
<!--                    />-->
<!--                  </div>-->
<!--                </el-upload>-->
<!--              </el-col>-->
<!--            </el-row>-->
          </el-form-item>
          <el-form-item label="提问" prop="score">
            <el-input
              v-model="form.issues_list"
              style="width: 100%"
              controls-position="right"
              placeholder="请输入问题"
              type="textarea"
            />
          </el-form-item>
          <el-form-item label="分值" prop="score">
            <el-input-number
              v-model="form.score"
              style="width: 100%"
              controls-position="right"
              placeholder="请输入分值"
            />
          </el-form-item>
          <el-form-item v-show="showAnswer" label="答案" style="margin-bottom: 10px">
            <el-form-item
              v-for="(domain, index) in form.answer"
              v-show="form.answer.length > 0"
              :key="index"
              label-width="0px"
              :label="mapAnswer(index)"
              :prop="mapAnswer(index)"
            >
              <el-row :gutter="10">
                <el-col :span="16" style="margin-top: 4px">
                  <Ckeditor v-model="domain[mapAnswer(index)]" />
<!--                  <el-image-->
<!--                    v-if="urlTest.test(domain[mapAnswer(index)])"-->
<!--                    style="height: 45px;width: 100%"-->
<!--                    :src="domain[mapAnswer(index)]"-->
<!--                  />-->
<!--                  <el-input v-else v-model="domain[mapAnswer(index)]" />-->
                </el-col>
<!--                <el-col :span="4">-->
<!--                  <el-upload-->
<!--                    :headers="headers"-->
<!--                    class="upload-demo"-->
<!--                    style="width: 40%"-->
<!--                    :action="$uploadUrl"-->
<!--                    :on-success="(file) => handleAnswer(file,index)"-->
<!--                    :show-file-list="false"-->
<!--                  >-->
<!--                    <div>-->
<!--                      <el-button-->
<!--                        type="text"-->
<!--                        icon="el-icon-picture-outline"-->
<!--                        style="margin-left: 20px;font-size: 20px"-->
<!--                      />-->
<!--                    </div>-->
<!--                  </el-upload>-->
<!--                </el-col>-->
                <el-col :span="3">
                  <el-button
                    style="font-size: 20px"
                    type="text"
                    icon="el-icon-delete"
                    @click.prevent="removeDomain(index)"
                  />
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button
                style="width: 100%;margin-top: 10px;margin-bottom: 15px"
                @click="addAnswer"
              >添加答案</el-button>
            </el-form-item>
          </el-form-item>
          <el-form-item label="正确答案" prop="correct_answer">
            <el-input v-model="form.correct_answer" placeholder="请输入正确答案（如：A或A-B）" />
          </el-form-item>
          <el-form-item label="题目解析" prop="analysis">
            <el-row>
              <el-col :span="20">
<!--                <div v-if="urlTest.test(form.analysis)" style="">-->
                <div v-if="analysis_imgs.length>0" style="">
                  <div class="analysis_imgs_card" v-for="(item,i) in analysis_imgs" style="display: flex;margin-bottom: 10px;">
                    <img :src="item" class="avatar" style="width: auto">
                    <i
                      class="el-icon-delete"
                      style="margin: auto auto auto 10px;cursor: pointer"
                      @click="(event)=>analysisRemove(i)"
                    />
                  </div>
                </div>
                <el-input
                  v-else
                  v-model="form.analysis"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入内容"
                />
              </el-col>
              <el-col :span="4">
                <el-upload
                  :headers="headers"
                  class="upload-demo"
                  style="width: 40%"
                  :action="$uploadUrl"
                  :on-success="handleAnalysis"
                  :show-file-list="false"
                >
                  <div>
                    <el-button
                      type="text"
                      icon="el-icon-picture-outline"
                      style="margin-left: 20px;font-size: 20px"
                    />
                  </div>
                </el-upload>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-drawer>
    </template>
  </BasicLayout>
</template>

<script>
import {
  getQuestionList,
  addQuestion,
  editQuestion,
  delQuestion
} from '@/api/admin/sys-question'
import { getSubject, getConfigKey } from '@/api/admin/sys-course'
import { getToken } from '@/utils/auth'
// import Ckeditor from '@/components/richText/ckEditor.vue'
import Ckeditor from '@/components/richText/ckEditor4.vue'
export default {
  name: 'SysTestPaperManage',
  components: {
    Ckeditor
  },
  data() {
    return {
      headers: { Authorization: 'Bearer ' + getToken() },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      visible: false,
      dataList: [],
      form: {
        answer: []
      },
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        ex_type: [{ required: true, message: '选择类型', trigger: 'blur' }],
        subject: [{ required: true, message: '选择科目', trigger: 'blur' }],
        public_range: [
          { required: true, message: '选择公开范围', trigger: 'blur' }
        ],
        province: [{ required: true, message: '选择适用地区', trigger: 'blur' }]
      },
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        name: undefined,
        type: undefined,
        subject: undefined
      },
      subjectList: [],
      topicType: {},
      showAnswer: true,
      topicContent: null,
      urlTest: /^http(s|):\/\/\S*?\//,
      analysis_imgs:[]
    }
  },
  created() {
    this.getList()
    getSubject().then(res => {
      this.subjectList = res?.data || []
    })
    getConfigKey().then(response => {
      this.topicType = JSON.parse(response?.data?.configValue)
    })
  },
  methods: {
    getList() {
      this.loading = true
      try {
        getQuestionList(this.queryParams)
          .then(response => {
            this.dataList = response.data.list
            this.total = response.data.count
          })
          .finally(() => {
            this.loading = false
          })
      } catch (error) {
        console.log(error)
      }
    },
    // 取消按钮
    cancel() {
      this.visible = false
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
      this.topicContent = null
      this.showAnswer = true
    },
    parentIdFormat(row) {
      return this.selectItemsLabel(this.parentIdOptions, row.parentId)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 排序回调函数 */
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (this.order !== '' && this.order !== prop + 'Order') {
        this.queryParams[this.order] = undefined
      }
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
        this.order = prop + 'Order'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
        this.order = prop + 'Order'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      // this.reset()
      this.visible = true
      this.title = '添加'
      this.$set(this.form, 'answer', [])
    },
    handleUpdate(row) {
      // console.log(row)
      this.reset()
      this.visible = true
      this.title = '修改'
      this.form = {
        ...row,
        answer: row?.answer !== '' ? JSON.parse(row?.answer) : []
      }
      if (this.urlTest.test(row?.content)) {
        this.topicContent = row?.content
      }
      this.analysis_imgs = []
      if (this.urlTest.test(row?.analysis)) {
        this.analysis_imgs = row.analysis.split(',')
        // console.log(this.analysis_imgs)
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.analysis_imgs.length > 0) {
            this.form.analysis = this.analysis_imgs.join(',')
          }
          // console.log(this.form); return
          if (this.form.id !== undefined) {
            editQuestion(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.visible = false
                this.getList()
                this.form = {
                  answer: []
                }
              } else {
                this.msgError(response.msg)
              }
            })
            return
          }
          this.form.teaching_point =
            this.form.teaching_point ?? this.deptOptions?.[0].id
          addQuestion(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(response.msg)
              this.visible = false
              this.getList()
              this.form = {
                answer: []
              }
            } else {
              this.msgError(response.msg)
            }
          })
        }
      })
    },
    handleDelete(row) {
      const ids = (row.id && [row.id]) || this.ids
      this.$confirm('是否确认删除该数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return delQuestion({ ids })
        })
        .then(response => {
          if (response.code === 200) {
            this.msgSuccess(response.msg)
            this.getList()
          } else {
            this.msgError(response.msg)
          }
        })
        .catch(function() {})
    },
    addAnswer() {
      if (this.form?.answer && this.form?.answer?.length > 5) {
        return
      }
      this.form?.answer?.push({})
    },
    removeDomain(key) {
      const temp = this.form.answer
        .filter((value, index) => index !== key)
        .map((item, index) => {
          let s = ''
          Object.values(item).forEach(element => {
            s = element
          })
          return {
            [this.mapAnswer(index)]: s
          }
        })
      this.form.answer = temp
    },
    mapAnswer(answer) {
      const answerArr = answer.toString().split(',')
      const newArr = answerArr.map(item =>
        String.fromCharCode(65 + parseInt(item))
      )
      return newArr.join(',')
    },
    changeType(value) {
      if (value === '应用题') {
        this.showAnswer = false
      } else if (value === '简答题') {
        this.showAnswer = false
      } else {
        this.showAnswer = true
      }
    },
    handleAnswer(file, index) {
      const parms = this.form.answer.map((v, i) => {
        const result = {
          ...v
        }
        if (index === i) {
          result[
            this.mapAnswer(index)
          ] = file.data.full_path
        }
        return result
      })
      this.form.answer = parms
    },
    handleSuccess(file) {
      this.form = {
        ...this.form,
        content: file.data.full_path
      }
      this.topicContent = file.data.full_path
    },
    handleAnalysis(file) {
      this.analysis_imgs.push(file.data.full_path)
      this.form = {
        ...this.form,
        // analysis: file.data.full_path
        analysis: this.analysis_imgs.join(',')
      }
    },
    analysisRemove(i) {
      this.analysis_imgs.splice(i, 1)
      if (this.analysis_imgs.length > 0) {
        this.form.analysis = this.analysis_imgs.join(',')
      } else {
        this.form.analysis = ''
      }
    },
    beforeRemove() {
      this.form.content = ''
      this.topicContent = ''
      // return this.$confirm(`确定移除？`)
      //   .then(() => {

      //   })
      //   .catch(() => {});
    }
  }
}
</script>
